﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using VkApiVer2.Properties;

namespace VkApiVer2
{
    static class SettingsManager
    {
        static public void SerializeToXML(List<User> usersData, string path)
        {
            var serializer = new XmlSerializer(typeof(List<User>));
            TextWriter textWriter = new StreamWriter(path);
            serializer.Serialize(textWriter, usersData);
            textWriter.Close();

        }
        static public List<User> DeserializeFromXML(string path)
        {
            var deserializer = new XmlSerializer(typeof(List<User>));
            TextReader textReader = new StreamReader(path);
            List<User> data;
            data = (List<User>)deserializer.Deserialize(textReader);
            textReader.Close();

            return data;
        }

        public static void Save()
        {
            var users = DeserializeFromXML(Settings.Default[SettingsConstants.UserSettings].ToString());
            foreach(User user in users)
            {
                if(user.Username.Equals(Settings.Default[SettingsConstants.UserName]))
                {
                    user.AccessToken = (string)Settings.Default[SettingsConstants.Token];
                    user.Expire = (DateTime)Settings.Default[SettingsConstants.Expire];
                    user.Id = (string)Settings.Default[SettingsConstants.UserId];
                    break;
                }
            }
            SerializeToXML(users, (string)Settings.Default[SettingsConstants.UserSettings]);

        }
    }


    [XmlType("User")]
    public class User
    {
        [XmlAttribute("username", DataType = "string")]
        public string Username { get; set; }

        [XmlElement("accessToken", IsNullable = true, DataType = "string")]
        public string AccessToken { get; set; }

        [XmlElement("expire")]
        public DateTime Expire { get; set; }

        [XmlElement("password", DataType = "string")]
        public string Password { get; set; }

        [XmlElement("userid", IsNullable = true, DataType = "string")]
        public string Id { get; set; }


    }

    [XmlRoot("UserList")]
    [XmlInclude(typeof(User))] // include type class User
    public class UserList
    {
        [XmlArray("UserArray")]
        [XmlArrayItem("User")]
        public List<User> Users = new List<User>();

        [XmlElement("UserId")]
        public string UserId { get; set; }

        // Konstruktoren 

        public void AddUser(User user)
        {
            Users.Add(user);
        }
    }

}
